<?php

namespace App\Kuafu\Product\Controller\Pos;

use App\Exceptions\BaseException;
use App\Kuafu\Base\Enum\ClientEnum;
use App\Kuafu\Base\Enum\DBEnum;
use App\Kuafu\Category\Service\CategoryService;
use App\Kuafu\Config\Service\ConfigService;
use App\Kuafu\Product\Enum\CodeEnum;
use App\Kuafu\Product\Enum\ProductCodeEnum;
use App\Kuafu\Product\Exceptions\ProductException;
use App\Kuafu\Product\Service\ProductService;
use App\Kuafu\Product\Validate\ProductNewValidate;
use App\Kuafu\Product\Validate\ProductValidate;
use App\Kuafu\ProductMenu\Enum\ProductMenuCodeEnum;
use App\Kuafu\ProductMenu\Exceptions\ProductMenuException;
use App\Kuafu\ProductMenu\Model\ProductMenu;
use App\Kuafu\ProductMenu\Service\ProductMenuService;
use App\Kuafu\Shop\Enum\ShopCodeEnum;
use App\Kuafu\Shop\Exceptions\ShopException;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\User\Exceptions\UserException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Kuafu\Base\Controller\BaseController;
use Illuminate\Validation\ValidationException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class ProductController extends BaseController
{
    /**
     * 店铺下的菜单、菜品、分类列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Kuafu\Shop\Exceptions\ShopException
     */
    public function lists(Request $request)
    {
        $updatedAt = $request->get('updatedAt', 0);
        $status    = $request->get('status', 0); // 0 , 1 查询对应值 -1 查询所有

        // 店铺的菜单信息
        $shop   = ShopService::getShopInfo($this->shopId);
        $menuId = $shop->menuId ?? 0;
        if (!$menuId) {
            return $this->fail(ProductCodeEnum::ERR_PRODUCT_NO_MENU);
        }
        $menu = ProductMenu::query()->select('id', 'name', 'desc', 'createdAt', 'updatedAt')->find($menuId);
        if (!$menu || $menu->status != DBEnum::STATUS_ON) {
            return $this->fail(ProductMenuCodeEnum::ERR_FOOD_MENUS_NULL_OFFLINE,
                ProductMenuCodeEnum::getCodeText(ProductMenuCodeEnum::ERR_FOOD_MENUS_NULL_OFFLINE));
        }
        $menu              = $menu->toArray();
        $menu['createdAt'] = strtotime($menu['createdAt']);
        $menu['updatedAt'] = strtotime($menu['updatedAt']);
        $data['menu']      = $menu;
        // 有新变动才返回数据
        if ($updatedAt < $menu['updatedAt']) {
            // 菜品列表
            $oriList = ProductMenuService::shopProductLists(ClientEnum::CLIENT_PRODUCT_POS, $status);
            // 分类信息
            $productList = [];
            $field       = ['id', 'name', 'sort'];
            $data        = CategoryService::filterNoProductCategory($this->brandId, $menuId, $field, $oriList,
                $productList, 1);

            $productList  = $data['productList'];
            $categoryList = $data['categoryList'];
        }
        $data = [
            'menu'         => $menu,
            'productList'  => $productList ?? null,
            'categoryList' => $categoryList ?? null,
        ];


        if ($status == DBEnum::QUERY_STATUS_ALL) {
            $maxOnlineCount    = (int)ConfigService::getCustomProductMaxOnlineCount();
            $nowOnlineCount    = (int)ProductService::getExistsCustomProductNum($this->shopId, $this->brandId);
            $data['remainNum'] = ($maxOnlineCount - $nowOnlineCount) < 0 ? 0 : $maxOnlineCount - $nowOnlineCount;
        }


        return $this->success($data);
    }

    /**
     * 修改店铺菜品的自定义状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Kuafu\ProductMenu\Exceptions\ProductMenuException
     * @throws \App\Kuafu\Product\Exceptions\ProductException
     */
    public function doStatus(Request $request)
    {
//        $productId = $request->post('productId');
//        $status    = $request->post('status');
//        $out       = $request->post('out');
//        $valid     = ProductValidate::doStatus($request);
//        if ($valid) {
//            return $this->fail(ProductCodeEnum::ERR_PRODUCT_NOT_INPUT, $valid);
//        }
//        ShopService::doProductStatus($productId, $status, $out);
//        return $this->success(['productId' => $productId]);

        $shopId    = $request->header("shopId", 0);
        $brandId   = $request->header("brandId", 0);
        $productId = $request->post('productId');
        $params    = ProductNewValidate::posStatusValidate($request->merge(["id" => $productId])->all());
        ProductService::posStatus($shopId, $brandId, $params);
        return $this->success();
    }


    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ProductException
     * @throws ValidationException
     * @throws NotFoundExceptionInterface|ContainerExceptionInterface
     */
    public function insert(Request $request): JsonResponse
    {
        $brandId = $request->header('brandId', 0);
        $shopId  = $request->header('shopId', 0);
        ProductService::insert(
            $shopId,
            $brandId,
            ProductNewValidate::posInsertValidate(
                $request->merge(["type" => CodeEnum::PRODUCT_TYPE_PACKAGE])->all()
            )
        );
        return $this->success();
    }

    /**
     * 编辑菜品
     *
     * @param Request $request
     * @param int $productId
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ProductException
     * @throws ValidationException
     */
    public function update(Request $request, int $productId): JsonResponse
    {
        $shopId  = $request->header("shopId", 0);
        $brandId = $request->header("brandId", 0);
        ProductService::update(
            $shopId,
            $brandId,
            ProductNewValidate::posUpdateValidate(
                $productId,
                $request->merge([
                    "id"   => $productId,
                    "type" => CodeEnum::PRODUCT_TYPE_PACKAGE
                ])->all()
            )
        );
        return $this->success();
    }

    /**
     * 菜品详情
     *
     * @param Request $request
     * @param int $productId
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ProductException
     * @throws ValidationException
     */
    public function detail(Request $request, int $productId): JsonResponse
    {
        $brandId = $request->header('brandId', 0);
        $shopId  = $request->header('shopId', 0);
        ProductNewValidate::detailValidate($request->merge(["id" => $productId])->all());
        return $this->success(ProductService::detail($productId, $shopId, $brandId));
    }


    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ProductException
     */
    public function ordinaryProducts(Request $request): JsonResponse
    {
        $shopId  = $request->header("shopId", 0);
        $brandId = $request->header('brandId', 0);
        return $this->success(ProductService::ordinaryProducts($shopId, $brandId));
    }

    /**
     * 修改菜品状态
     *
     * @param Request $request
     * @param int $productId
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ProductException
     * @throws ProductMenuException
     * @throws ShopException
     * @throws ValidationException
     * @throws BaseException
     */
    public function status(Request $request, int $productId): JsonResponse
    {
        $shopId  = $request->header("shopId", 0);
        $brandId = $request->header("brandId", 0);
        $params  = ProductNewValidate::posStatusValidate($request->merge(["id" => $productId])->all());
        ProductService::posStatus($shopId, $brandId, $params);
        return $this->success();
    }

    /**
     * @param Request $request
     * @param int $productId
     * @return JsonResponse
     * @throws BaseException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ProductException
     * @throws UserException
     * @throws ValidationException
     */
    public function delete(Request $request, int $productId): JsonResponse
    {
        $shopId  = $request->header("shopId", 0);
        $brandId = $request->header("brandId", 0);

        $params = ProductNewValidate::posDeleteValidate($request->merge(["id" => $productId])->all());
        ProductService::delete($shopId, $brandId, $params);
        return $this->success();
    }
}
